<template>
  <div>
    <slot name="before"></slot>

    <table class="table table-sm table-bordered approve-table">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="16%" />
        <col width="34%" />
      </colgroup>
      <tbody>
        <tr>
          <td>{{ approveData.label }}</td>
          <td colspan="3" class="report-input-td">
            <slot name="inner"></slot>

            <div v-for="(r, index) of records" :key="index" class="p-item">
              <record-item :record-data="r"></record-item>
            </div>

            <div v-if="isEdit" class="bg-edit">
              <textarea
                rows="3"
                class="form-control"
                placeholder="请填写意见"
                v-model="approveForm.approval_option"
              ></textarea>
              <div class="p-2 d-flex justify-content-between">
                <div>签字：{{ approveForm.approval_person || '' }}</div>
                <div class="w-50">日期：{{ approveForm.dateStr || '' }}</div>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <slot name="after"></slot>

    <div class="text-center my-3" v-if="isEdit">
      <el-button
        class="btn-long"
        type="primary"
        :loading="passLoading"
        :disabled="loading"
        @click="handlePass"
      >
        通过
      </el-button>
      <el-button
        v-if="approveData.rekey"
        class="btn-long"
        type="warning"
        :loading="returnLoading"
        :disabled="loading"
        @click="handleReturn"
      >
        退回
      </el-button>
      <el-button
        class="btn-long"
        type="danger"
        :loading="rejectLoading"
        :disabled="loading"
        @click="handleReject"
      >
        不通过
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addApprove, updateApprove } from '@/credit/mixin/wf'
import RecordItem from '@/credit/views/county/unionProvince/components/projectApprove/RecordItem'

export default {
  components: {
    RecordItem,
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
    approveData: {
      type: Object,
      default: () => ({
        editable: false,
        record: [],
      }),
    },
    beforeSave: {
      type: Function,
      default: () => true,
    },
  },
  data() {
    return {
      passLoading: false,
      returnLoading: false,
      rejectLoading: false,

      approveForm: {
        approval_option: '',
        approval_person: '',
        dateStr: '',
        id: '',
        task_id: '',
      },
    }
  },
  computed: {
    ...mapGetters(['user']),
    relatedId() {
      return this.relatedData.customer_related_id
    },
    editable() {
      return this.approveData.editable
    },
    isEdit() {
      return !this.viewMode && this.editable
    },
    loading() {
      return this.passLoading || this.returnLoading || this.rejectLoading
    },
    records() {
      return this.approveData.record.filter(it => !it.editable)
    },
  },
  watch: {
    approveData: {
      handler: function (val) {
        this.init(val)
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    init(val) {
      for (const r of val.record) {
        if (r.editable) {
          Object.keys(this.approveForm).forEach(key => {
            this.approveForm[key] = r[key] || ''
          })
          break
        }
      }
    },

    validateOpinion() {
      if (!this.approveForm.approval_option) {
        this.$message.warning('请输入审批意见')
        return false
      }
      return true
    },

    async handlePass() {
      if (!this.validateOpinion()) {
        return
      }

      const bs = this.beforeSave()
      if (bs === false) return
      try {
        if (bs && bs.then) {
          this.passLoading = true
          const res = await bs.then()
          if (res === false) return
        }
      } catch (err) {
        return
      } finally {
        this.passLoading = false
      }

      this.passLoading = true
      return this.addApproveData(1)
        .then(res => {
          this.$message.success('操作成功！')
          this.$emit('success', res)
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || `操作失败，请重试！`)
        })
        .finally(() => {
          this.passLoading = false
        })
    },

    async handleReject() {
      if (!this.validateOpinion()) {
        return
      }

      this.$utils
        .msgbox({
          message: `确定拒绝项目：${this.relatedData.enterprise_name}?`,
          type: 'error',
          beforeClose: () => {
            this.rejectLoading = true
            return this.addApproveData(2).finally(() => {
              this.rejectLoading = false
            })
          },
        })
        .then(res => {
          this.$message.success('操作成功！')
          this.$emit('success', res)
        })
        .catch(() => {
          this.$message.error('操作失败，请重试！')
        })
    },

    async handleReturn() {
      if (!this.validateOpinion()) {
        return
      }

      this.$utils
        .msgbox({
          message: `确定退回项目：${this.relatedData.enterprise_name}?`,
          type: 'warning',
          beforeClose: () => {
            this.returnLoading = true
            return this.addApproveData(3).finally(() => {
              this.returnLoading = false
            })
          },
        })
        .then(res => {
          this.$message.success('操作成功！')
          this.$emit('success', res)
        })
        .catch(() => {
          this.$message.error('操作失败，请重试！')
        })
    },

    addApproveData(status) {
      const { id, approval_option: opinion, task_id: taskId } = this.approveForm
      const { process } = this.approveData
      const data = {
        opinion,
        status,
        process,
        taskId,
        rekey: status === 3 ? this.approveData.rekey : null,
      }

      return id ? updateApprove(id, data, this.user) : addApprove(this.relatedId, data, this.user)
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
